package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.article.entity.ApAuthor;
import com.heima.article.feign.ArticleFeign;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.entity.WmUser;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-05-15
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService userFollowService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    public String followBehaviorTopic;

    /**
     * 自媒体用户登录
     *
     * @param dto 登录参数 - md5（用户填写密码+数据库中盐）
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.参数校验 入参是否为空（TODO 采用参数校验框架来优化）
        if (dto == null || (StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword()) && StringUtils.isBlank(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据账户手机号 查询APP用户记录（得到密文，盐）
        if (StringUtils.isNotBlank(dto.getPhone())) {
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser apUser = this.getOne(queryWrapper);
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            if (apUser.getStatus() == 1) {
                //说明用户锁定
                return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
            }
            //3.校验密码是否正确
            //3.1 将用户填写密码+salt 进行MD5密码
            String userEnterPwd = dto.getPassword() + apUser.getSalt();
            String userEnterEncodedStr = DigestUtils.md5DigestAsHex(userEnterPwd.getBytes());

            //3.2 根据用户录入密码密文跟数据库正确密文进行比较
            if (!userEnterEncodedStr.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //4.根据用户信息生成令牌
            //4.1 根据用户信息生成令牌（用户ID，名称）
            HashMap<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId", apUser.getId());
            claimMaps.put("userName", apUser.getName());
            String token = AppJwtUtil.getToken(claimMaps);

            //4.2 对用户对象信息进行脱敏处理
            apUser.setPassword(null);
            apUser.setSalt(null);
            apUser.setPhone(null);

            //5.按照接口文档封装响应结果对象
            HashMap<String, Object> mapResult = new HashMap<>();
            mapResult.put("user", apUser);
            mapResult.put("token", token);

            return ResponseResult.okResult(mapResult);
        }
        //3. 用户选择 不登录，先看看 则采用匿名登录
        if (StringUtils.isNotBlank(dto.getEquipmentId())) {
            //构建jwt载荷信息
            HashMap<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId", 0);
            claimMaps.put("equipmentId", dto.getEquipmentId());
            String token = AppJwtUtil.getToken(claimMaps);
            //5.按照接口文档封装响应结果对象
            HashMap<String, Object> mapResult = new HashMap<>();
            mapResult.put("token", token);
            return ResponseResult.okResult(mapResult);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }


    /**
     * 登录用户 关注/取消 关注某个作者
     *
     * @param dto 文章ID  文章作者ID  操作类型：0 关注  1: 取消  设备ID
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.先获取登录用户
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.构建关注实体类对象
        ApUserFollow apUserFollow = new ApUserFollow();
        //2.1 设置当前登录用户信息
        apUserFollow.setUserId(user.getUserId());
        apUserFollow.setUserName(user.getUserName());
        //2.2 设置关注作者 用户信息
        //2.2.1 远程调用文章微服务得到作者信息
        ResponseResult<ApAuthor> result = articleFeign.getAuthorById(dto.getAuthorId());
        if (result.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = result.getData();
            apUserFollow.setFollowId(apAuthor.getUserId());
            apUserFollow.setFollowName(apAuthor.getName());
        }
        //2.3 设置关注级别
        apUserFollow.setLevel(UserEnum.USER_FOLLOW_LEVEL_ONCE.getVal());

        //3.根据用户操作类型，保存关注记录
        //3.1 封装查询条件 查询关注记录
        LambdaQueryWrapper<ApUserFollow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUserFollow::getUserId, user.getUserId());
        queryWrapper.eq(ApUserFollow::getFollowId, dto.getAuthorId());
        Integer operation = dto.getOperation();
        if (operation.equals(UserEnum.USER_FOLLOW_OPRATION.getVal())) {
            //关注操作
            ApUserFollow one = userFollowService.getOne(queryWrapper);
            if (one == null) {
                //第一次关注 直接保存
                userFollowService.save(apUserFollow);
            }
        } else {
            //取消关注
            userFollowService.remove(queryWrapper);
        }
        //4.发送关注行为消息到Kafka。为后续行为服务获取行为记录提供数据
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setFollowId(apUserFollow.getFollowId());
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        followBehaviorDto.setOperation(operation);
        String dataStr = JSON.toJSONString(followBehaviorDto);
        kafkaTemplate.send(followBehaviorTopic, dataStr);
        return ResponseResult.okResult();
    }
}
